package cn.bytepulse.utils;

import cn.bytepulse.web.admin.entity.SysAssets;
import cn.bytepulse.web.admin.mapper.SysAssetsMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.UUID;

import static cn.bytepulse.utils.GenerateUtils.generateRandomNumber;

/**
 * @author jiejiebiezheyang
 * @since 2025-03-28 20:00
 */
@Component
@RequiredArgsConstructor
public class AssetsUtils {

    private final MinioUtils minioUtils;

    private final SysAssetsMapper sysAssetsMapper;

    /**
     * 保存文件
     *
     * @param relationType   关联类型
     * @param relationNumber 关联编号
     * @param newFilename    新文件名
     * @param file           文件
     * @param unique         同一关联类型和关联编号下, 文件是否只能唯一存在
     */
    public SysAssets saveAssets(String relationType, String relationNumber, String newFilename, MultipartFile file, boolean unique) throws Exception {
        if (unique) { // 如果唯一, 删除旧
            QueryWrapper<SysAssets> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("relation_type", relationType)
                    .eq("relation_number", relationNumber);
            SysAssets assets = sysAssetsMapper.selectOne(queryWrapper);
            // 有旧文件, 则删除
            if (assets != null) {
                deleteFile(assets.getId());
            }
        }
        newFilename = newFilename + "-" + generateRandomNumber(4);
        // 文件原名
        String oldFileName = file.getOriginalFilename();
        // 获取后缀
        String suffix = "";
        if (oldFileName != null) {
            suffix = oldFileName.substring(oldFileName.lastIndexOf(".") + 1);
        }
        // 最终文件名
        newFilename = newFilename + "." + suffix;
        // minio对象名
        String objectName = relationType + "/" + relationNumber + "/" + newFilename;
        String projectDir = System.getProperty("user.dir");
        projectDir = projectDir.endsWith("/") || projectDir.endsWith("\\") ? projectDir : projectDir + "/";
        String uuid = UUID.randomUUID().toString().replace("-", "");
        File temp = new File(projectDir + uuid + suffix);
        file.transferTo(temp);
        minioUtils.uploadFile(objectName, temp);
        if (temp.exists()) {
            temp.delete();
        }
        SysAssets sysAssets = new SysAssets();
        sysAssets.setRelationType(relationType);
        sysAssets.setRelationNumber(relationNumber);
        sysAssets.setOldName(oldFileName);
        sysAssets.setFilename(newFilename);
        sysAssets.setFileType(suffix);
        sysAssets.setObjectKey(objectName);
        sysAssets.setUploadTime(new Date());
        sysAssets.setModifyTime(new Date());
        sysAssetsMapper.insert(sysAssets);
        return sysAssets;

    }

    /**
     * 删除文件
     *
     * @param assetsId 资源Id
     */
    public void deleteFile(Integer assetsId) throws Exception {
        SysAssets files = sysAssetsMapper.selectById(assetsId);
        if (files != null) {
            String objectKey = files.getObjectKey();
            // 删除存储对象
            if (minioUtils.fileExists(objectKey)) {
                minioUtils.deleteFile(objectKey);
            }
            // 删除表记录
            sysAssetsMapper.deleteById(assetsId);
        }
    }
}
